package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"rk155/models/mysql"
	"time"

	"rk155/rk155rpc/internal/svc"
	"rk155/rk155rpc/rk155rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *rk155rpc.RegisterRequest) (*rk155rpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	Intn := rand.Intn(900000000) + 100000000
	WxChatName := fmt.Sprintf("wx%d%s", Intn, time.Now().Format("20060102150405"))
	mysql.DB.Debug().Model(&user).Where("wxchatname = ?", in.WxChatName).Find(&user)

	if user.WxChatName == WxChatName {
		return nil, fmt.Errorf("微信号已经存在,请重新生成")
	}

	register := mysql.User{
		Model:      gorm.Model{},
		Tel:        in.Tel,
		Password:   in.Password,
		HeadImg:    in.HeadImg,
		UserId:     int(in.UserId),
		WxChatName: WxChatName,
	}
	err := mysql.DB.Debug().Model(&register).Create(&register).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	return &rk155rpc.RegisterResponse{Id: int64(register.ID)}, nil
}
